<script lang="ts" setup name="marketingMemberEdit">
import { ref } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import { getMemberList, getUserCategoryList } from "@/api/modules/member";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { genderType, memberStatus } from "@/utils/serviceDict";
import { getStoreList } from "@/api/modules/operation";
import { grantMessageAPI, createMessageAPI } from "@/api/modules/activity";
import GrantDialog from "./components/grantDialog.vue";
import { ElMessage, ElTable } from "element-plus";
import { FormData } from "./components/grantDialog.vue";
import { useRouter } from "vue-router";
import { ArrowLeft } from "@element-plus/icons-vue";
import { Member } from "@/api/interface";

const router = useRouter();

const multipleTableRef = ref<InstanceType<typeof ElTable> | null>(null);

const dataCallback = (data: any) => {
  return {
    list: data.list,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};
const proTableRef = ref<ProTableInstance>();

// 右侧表格
const columns: ColumnProps<Member.ResMemberList>[] = [
  { type: "selection", label: "序号", width: 60 },
  { prop: "nickName", label: "会员名称", minWidth: 100, align: "left", search: { el: "input", key: "content" } },
  {
    prop: "number",
    label: "会员卡号",
    align: "left",
    minWidth: 100
  },
  {
    prop: "categoryName",
    label: "会员分类",
    align: "left",
    minWidth: 100,
    enum: () => getUserCategoryList({ pageNum: 1, pageSize: 999 }),
    search: {
      el: "select",
      key: "categoryId"
    },
    fieldNames: { label: "name", value: "id" }
  },
  { prop: "mobile", label: "电话号码", minWidth: 100, align: "left" },
  {
    prop: "gradeName",
    label: "会员等级",
    align: "left",
    enum: () => getStoreList({ pageNum: 1, pageSize: 999 }),
    search: { el: "select", key: "storeId", label: "店铺搜索", props: { filterable: true } },
    fieldNames: { label: "storeName", value: "id" },
    minWidth: 80
  },
  {
    prop: "sex",
    label: "性别",
    // 字典数据
    // enum: genderType,
    // 字典请求不带参数
    enum: genderType,
    align: "left",
    width: 80,
    // 字典请求携带参数
    // enum: () => getUserGender({ id: 1 }),
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "status",
    label: "状态",
    enum: memberStatus,
    width: 80,
    align: "left",
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "label", value: "value" }
  },
  {
    prop: "balance",
    label: "储值余额",
    align: "left",
    width: 150,
    search: {
      el: "date-picker",
      key: "birthDayRange",
      label: "生日范围",
      props: {
        type: "datetimerange",
        format: "MM-DD ",
        valueFormat: "MM-DD"
      }
    }
  },
  { prop: "point", label: "积分", align: "left", width: 100 }
];

const selectList = ref<any[]>([]); // 暂存勾选数据
const selectionChange = (e: any) => {
  selectList.value = e;
};
const tableData = ref<any[]>([]); // 左侧数据
const onAdd = () => {
  //  添加勾选数据
  tableData.value = JSON.parse(JSON.stringify(selectList.value));
  proTableRef.value?.replaceTableData(
    proTableRef.value?.tableData.filter(v => {
      if (!selectList.value.some(i => i.id === v.id)) return v;
    })
  );
};
// 重置数据
const onReset = () => {
  tableData.value = [];
  proTableRef.value?.getTableList();
  proTableRef.value?.selectionChange([]);
};
const leftCheckList = ref<any[]>([]);
const handleSelectionChange = (e: any[]) => {
  // 左侧表格选中
  leftCheckList.value = e;
};
const onTakeout = () => {
  // 左侧表格移开单条数据
  tableData.value = tableData.value.filter(v => {
    if (!leftCheckList.value.some(i => i.id === v.id)) return v;
  });
  proTableRef.value?.replaceTableData([...proTableRef.value?.tableData, ...leftCheckList.value]);
};

// 弹出层数据
const grantDialogRef = ref<InstanceType<typeof GrantDialog> | null>(null);
const grantMessage = async () => {
  if (tableData.value.length < 1) return ElMessage({ message: "请选择至少一个会员", type: "warning" });
  // const res = await grantMessageAPI();

  grantDialogRef.value?.acceptParams({
    title: "会员推送",
    // list: res.data,
    userIds: tableData.value.map(v => {
      return v.id;
    })
  });
};

// 创建短信
const onConfirm = async (e: FormData) => {
  new Promise((resolve, reject) => {
    createMessageAPI(e)
      .then(res => {
        resolve(true);
        ElMessage({ message: "短信编辑成功", type: "success" });
        grantDialogRef.value?.changeVisible(false);
        router.push("/marketing/marketing-member");
      })
      .catch(err => {
        console.log(err);
        reject(false);
      });
  });
};
</script>

<template>
  <div class="member-container">
    <div class="left">
      <el-page-header @back="router.back()" icon="ArrowLeft" style="padding: 5px">
        <template #content> <span class="text-large font-600 mr-3"> 创建短信 </span></template>
      </el-page-header>

      <div class="left-btn">
        <div style="font-size: 13px">已选择会员列表</div>
        <div>
          <el-button size="small" @click="onReset">清空</el-button>
          <el-button size="small" @click="grantMessage" type="primary">发放</el-button>
        </div>
      </div>
      <div style="margin-top: 10px; font-size: 12px; color: #606266">提示：选择会员后按添加按钮添加到左边的列表</div>
      <div class="left-table">
        <el-table border ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="40" />
          <el-table-column property="mobile" label="电话号码" />
          <el-table-column property="nickName" label="会员名称" />
        </el-table>
        <GrantDialog @confirm="onConfirm" ref="grantDialogRef"></GrantDialog>
      </div>
    </div>
    <div class="table-box table">
      <ProTable
        @reset="onReset"
        ref="proTableRef"
        :columns="columns"
        title="会员资料列表"
        row-key="id"
        :indent="20"
        :request-api="getMemberList"
        :data-callback="dataCallback"
        @selection-change="selectionChange"
      >
        <template #tableHeader>
          <div>
            <el-button @click="onTakeout">移出</el-button>
            <el-button type="primary" @click="onAdd">添加</el-button>
          </div>
        </template>
      </ProTable>
    </div>
  </div>
</template>

<style lang="scss" scoped>
div {
  box-sizing: border-box;
}
.member-container {
  display: flex;
  height: 82vh;
  .left {
    width: 300px;
    height: 100%;
    padding: 10px;
    margin-right: -1px;
    background-color: #ffffff;
    border: 1px solid #e4e7ed;
    .left-btn {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 20px;
    }
    .left-table {
      margin-top: 20px;
    }
  }
  .table {
    height: 100%;
  }
}
</style>
